package org.dce.screencapturer;

import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.JPopupMenu;

public class SystemTrayHandler
	implements MouseListener,
		MouseMotionListener,
		ActionListener{

	private final TrayIcon icon;
	private UI ui;
	private final JPopupMenu popup = new JPopupMenu();
	
	
	public SystemTrayHandler(UI ui)
		throws IOException{
		
		this.ui = ui;
		this.icon = new TrayIcon(ImageIO.read(UI.class.getResource("/images/tray-icon.png")));
		
		try {
			SystemTray.getSystemTray().add(icon);
			icon.addMouseListener(this);
		}catch (Exception ex){
			ex.printStackTrace();
		}
		
		popup.add(ui.getActions().get("actions.newFromClipboard"));
		popup.add(ui.getActions().get("actions.captureArea"));
		popup.add(ui.getActions().get("actions.capture"));
		popup.add(ui.getActions().get("actions.exit"));
		
		popup.setLightWeightPopupEnabled(false);
	}

	@Override
	public void mouseClicked(MouseEvent e) {

		if (e.getButton() == MouseEvent.BUTTON1){
			ui.setVisible(!ui.isVisible());
		}

	}

	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	public void mousePressed(MouseEvent e) {
		if (e.isPopupTrigger()){
			
			// Workaround as described at http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6285881
			
			popup.setLocation(e.getXOnScreen(),e.getYOnScreen());
			popup.setInvoker(popup);
			popup.setVisible(true);
		} 
	}
	public void mouseReleased(MouseEvent e) {}
	public void mouseDragged(MouseEvent e) {}
	public void mouseMoved(MouseEvent e) {}
	public void actionPerformed(ActionEvent e) {}

	public void close() {
		try {
			SystemTray.getSystemTray().remove(icon);
		}catch (Exception ex){
			ex.printStackTrace();
		}
	}
}
